import { Request, RequestHandler, Response } from 'express';
import {
  IGetRoleByIdReq,
  IAddRoleReq,
  IUpdateRoleReq,
  IDeleteRoleReq,
  IRole
} from '../../models/role.model';
import * as RoleService from '../services/role.service';
import * as PermissionsService from "../services/permission.service";

/**
 * Get active role records
 *
 * @param req Express Request
 * @param res Express Response
 */
export const getRoles: RequestHandler = async (req: Request, res: Response) => {
  try {
    const roles = await RoleService.getRoles();

    res.status(200).json({
      data: roles,
      code: 2000,
    })
  } catch (error) {
    console.error('[roles.controller][getRoles][Error] ', typeof error === 'object' ? JSON.stringify(error) : error);
    res.status(500).json({
      message: '角色列表获取失败！'
    });
  }
};

/**
 * Get role record based on id provided
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const getRoleById: RequestHandler = async (req: IGetRoleByIdReq, res: Response) => {
  try {
    const role = await RoleService.getRoleById(req.params.id);
    const permissionList = await PermissionsService.getPermissionsByIds(JSON.parse(role[0].rolePermissions.toString()));

    res.status(200).json({
      data: role,
      code: 2000,
    })
  } catch (error) {
    console.error('[roles.controller][getRoleById][Error] ', typeof error === 'object' ? JSON.stringify(error) : error);
    res.status(500).json({
      message: '角色信息获取失败！'
    });
  }
};

/**
 * Inserts a new role record
 *
 * @param req Express Request
 * @param res Express Response
 */
export const addRole: RequestHandler = async (req: IAddRoleReq, res: Response) => {
  try {
    req.body.rolePermissions = JSON.stringify(req.body.rolePermissions);
    const result = await RoleService.insertRole(req.body);

    res.status(200).json({
      data: result,
      code: 2000,
    })
  } catch (error) {
    console.error('[roles.controller][addRole][Error] ', typeof error === 'object' ? JSON.stringify(error) : error);
    if (error.code === 'ER_DUP_ENTRY') {
        res.status(500).json({
            message: '角色名称重复，请重新输入！'
          });
    } else {
        res.status(500).json({
            message: '角色保存失败！'
         });
    }
  }
};

/**
 * Updates existing role record
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const updateRoleById: RequestHandler = async (req: IUpdateRoleReq, res: Response) => {
  try {
    req.body.rolePermissions = JSON.stringify(req.body.rolePermissions);
    const result = await RoleService.updateRole({...req.body, id: req.params.id});

    res.status(200).json({
      data: result,
      code: 2000,
    })
  } catch (error) {
    console.error('[roles.controller][updateRoleById][Error] ', typeof error === 'object' ? JSON.stringify(error) : error);
    if (error.code === 'ER_DUP_ENTRY') {
        res.status(500).json({
            message: '角色名称重复，请重新输入！'
          });
    } else {
        res.status(500).json({
            message: '角色更新失败！'
         });
    }
  }
};

/**
 * deletes a role
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const deleteRoleById: RequestHandler = async (req: IDeleteRoleReq, res: Response) => {
  try {
    const result = await RoleService.deleteRole(req.params.id);

    res.status(200).json({
      data: result,
      code: 2000,
    })
  } catch (error) {
    console.error('[roles.controller][deleteRoleById][Error] ', typeof error === 'object' ? JSON.stringify(error) : error);
    res.status(500).json({
      message: '角色删除失败！'
    });
  }
};